package com.example.tool.window;

import com.intellij.icons.AllIcons;
import com.intellij.ui.JBColor;

import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;

public class HToolWindowView extends JPanel {
  private CardLayout cardLayout;
  private JPanel cardPanel;
  private final List<JPanel> pages;
  private final Map<Integer, Supplier<Boolean>> supplierMap = new HashMap<>();

  public HToolWindowView(List<JPanel> jPanels) {
    pages = jPanels;
  }

  public HToolWindowView next(int step, Supplier<Boolean> supplier) {
    supplierMap.put(step, supplier);
    return this;
  }

  /**
   * 构建页面
   */
  public HToolWindowView setup(AtomicInteger step) {
    setLayout(new BorderLayout());
    cardLayout = new CardLayout();
    cardPanel = new JPanel(cardLayout);
    for (int i = 0; i < pages.size(); i++) {
      JPanel jPanel = pages.get(i);
      cardPanel.add(jPanel, "Step" + (i + 1));
    }
    JButton prevButton = new JButton("上一步");
    prevButton.setIcon(AllIcons.Chooser.Left);
    prevButton.setBorderPainted(false);
    JButton nextButton = new JButton("下一步");
    nextButton.setIcon(AllIcons.Chooser.Right);
    nextButton.setOpaque(true);
    nextButton.setBorderPainted(false);
    nextButton.setContentAreaFilled(true);
    nextButton.setForeground(JBColor.BLUE);
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(prevButton);
    buttonPanel.add(nextButton);
    prevButton.setEnabled(false);
    nextButton.setEnabled(true);
    add(cardPanel, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.SOUTH);
    // 上一步按钮点击
    prevButton.addActionListener(e -> {
      cardLayout.previous(cardPanel);
      step.getAndDecrement();
      prevButton.setEnabled(step.get() > 0);
      nextButton.setEnabled(true);
    });
    // 下一步按钮点击
    nextButton.addActionListener(e -> {
      int stepInt = step.get();
      Supplier<Boolean> booleanSupplier = supplierMap.get(stepInt + 1);
      if (stepInt == pages.size() - 1) {
        // 最后一步
        if (booleanSupplier != null) {
          @SuppressWarnings("unused") Boolean b = booleanSupplier.get();
        }
      } else {
        if (booleanSupplier == null || booleanSupplier.get()) {
          cardLayout.next(cardPanel);
          step.getAndIncrement();
          prevButton.setEnabled(true);
          nextButton.setEnabled(true);
        }
      }
    });
    return this;
  }
}
